package com.qa.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qa.pojo.Users;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * Handler执行完成之后调用这个方法
	 */

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exc)
			throws Exception {

	}

	/**
	 * Handler执行之后，ModelAndView返回之前调用这个方法
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * Handler执行之前调用这个方法
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 获取请求的URL
		String url = request.getRequestURI();
		// URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制
		String login = request.getParameter("login");
		if (url.indexOf("login.do") >= 0 && login != null) {
			return true;
		}
		// 插入查询历史记录
		if (url.indexOf("insertHis.do") >= 0) {
			return true;
		}
		if (url.indexOf("getSchoolMacInfo.do") >= 0) {
			return true;
		}
		// 返回部门和项目组信息
		if (url.indexOf("getRegisterInfo.do") >= 0) {
			return true;
		}
		// 跳转到注册页面
		if (url.indexOf("register.do") >= 0) {
			return true;
		}
		// 注册
		if (url.indexOf("registerUser.do") >= 0) {
			return true;
		}
		// 获取Session
		HttpSession session = request.getSession();
		if (session.getAttribute("user") != null
				&& ((Users) session.getAttribute("user")).getUsersid() != null) {
			Cookie cookie1 = new Cookie("username", ((Users) request
					.getSession().getAttribute("user")).getUsername());
			response.addCookie(cookie1);
			request.setAttribute("username",
					((Users) session.getAttribute("user")).getUsername());
			return true;
		}
		// 不符合条件的，跳转到登录界面
		request.getSession().setAttribute("sessionDate",
				System.currentTimeMillis());
		request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,
				response);

		return false;
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}